package com.miaowang.salad.activity;

import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.activity.AutoActivity;
import prj.carmap.mobile.activity.LiveActivity;
import prj.carmap.mobile.activity.LoginActivity;
import prj.carmap.mobile.activity.MainActivity;
import prj.carmap.mobile.activity.ProfileActivity;
import prj.carmap.mobile.model.UserInfo;
import prj.carmap.mobile.process.AutoServiceProcess;
import prj.carmap.mobile.process.LiveServiceProcess;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.ActionBar.LayoutParams;
import com.miaowang.salad.Common;
import com.miaowang.salad.data.OkHttpResponseData;
import com.miaowang.salad.jobqueue.GetCurrentTaskJob;
import com.miaowang.salad.jobqueue.JobEvents;
import com.miaowang.salad.jobqueue.ServiceRequestJob;
import com.miaowang.salad.util.CheckUtil;
import com.miaowang.salad.util.PrefUtils;
import com.path.android.jobqueue.Job;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class SaladMainActivity extends SherlockActivity {

	View view;
	LinearLayout layout_tuoche;
	LinearLayout layout_songdian;
	LinearLayout layout_huantai;
	LinearLayout layout_other;
	private ProgressDialog pd;
	private String currentTaskType = "";// 当前任务类型
	private String phoneNum = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this);
		CarmapApplication.currentPage = "salad";
		CarmapApplication.addActivity(this);
		setContentView(R.layout.fragment_main_page);
		initTitle();
		initComponent();
		initMenuItem();
		initControl();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void initTitle() {
		View customNav = LayoutInflater.from(this).inflate(
				R.layout.nav_seller_title_view, null);
		// Attach to the action bar
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT, Gravity.CENTER);
		getSupportActionBar().setCustomView(customNav);
		customNav.setLayoutParams(lp);
		Button returnBtn = (Button) customNav.findViewById(R.id.return_prev);
		returnBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
					public void onClick(View v) {
						// AutoActivity.this.startActivity(new Intent(
						// AutoActivity.this, MainActivity.class));
						SaladMainActivity.this.startActivity(new Intent(
								SaladMainActivity.this, MainActivity.class));
						((Activity) SaladMainActivity.this).finish();
					}
				});
		((TextView) customNav.findViewById(R.id.nav_title)).setText(this
				.getString(R.string.rescue_info_title));
		Button mapBtn = (Button) customNav.findViewById(R.id.return_map);
		mapBtn.setVisibility(View.GONE);
	}

	private void initMenuItem() {
		if ("live".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_type);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_type_image);
			itemImage.setImageResource(R.drawable.type_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_type_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}
		if ("auto".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_home);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_home_image);
			itemImage.setImageResource(R.drawable.front_page);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_home_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}
		// else if ("search".equals(CarmapApplication.currentPage)) {
		// // 底部菜单项
		// View menuItem = this.findViewById(R.id.menu_item_search);
		// menuItem.setBackgroundDrawable(getApplication().getResources()
		// .getDrawable(R.drawable.bottom_background));
		// // 底部菜单图标
		// ImageView itemImage = (ImageView) this
		// .findViewById(R.id.item_search_image);
		// itemImage.setImageResource(R.drawable.search_select);
		// // 底部菜单文字
		// TextView itemText = (TextView) this
		// .findViewById(R.id.item_search_text);
		// itemText.setTextColor(getApplication().getResources().getColor(
		// R.color.white));
		// }
		else if ("mine".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_mine);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_mine_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_mine_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		} else if ("salad".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_salad);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_salad_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_salad_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}

		// else if ("more".equals(CarmapApplication.currentPage)) {
		// // 底部菜单项
		// View menuItem = this.findViewById(R.id.menu_item_more);
		// menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
		// // 底部菜单图标
		// ImageView itemImage = (ImageView)
		// this.findViewById(R.id.item_more_image);
		// itemImage.setImageResource(R.drawable.more_select);
		// // 底部菜单文字
		// TextView itemText = (TextView)
		// this.findViewById(R.id.item_more_text);
		// itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		// }
	}

	private void initComponent() {
		layout_tuoche = (LinearLayout) findViewById(R.id.tuoche);
		layout_songdian = (LinearLayout) findViewById(R.id.songdian);
		layout_huantai = (LinearLayout) findViewById(R.id.huantai);
		layout_other = (LinearLayout) findViewById(R.id.other);
	}

	private void initControl() {
		layout_tuoche.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CheckUtil.isEmpty(PrefUtils.getString(
						SaladMainActivity.this, Common.PREF_MY_INFO, ""))) {
					Toast.makeText(SaladMainActivity.this, "您未设置个人信息，请先录入个人信息",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Log.i("TAG", "TUOCHE");
				currentTaskType = "拖车牵引";
				getCurrentTask(phoneNum);
				// jumpToActivityByType("拖车牵引");
			}
		});
		layout_songdian.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CheckUtil.isEmpty(PrefUtils.getString(
						SaladMainActivity.this, Common.PREF_MY_INFO, ""))) {
					Toast.makeText(SaladMainActivity.this, "您未设置个人信息，请先录入个人信息",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Log.i("TAG", "SONGDIAN");
				currentTaskType = "接电服务";
				getCurrentTask(phoneNum);
				// jumpToActivityByType("接电服务");
			}
		});
		layout_huantai.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CheckUtil.isEmpty(PrefUtils.getString(
						SaladMainActivity.this, Common.PREF_MY_INFO, ""))) {
					Toast.makeText(SaladMainActivity.this, "您未设置个人信息，请先录入个人信息",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Log.i("TAG", "HUANTAI");
				currentTaskType = "更换轮胎";
				getCurrentTask(phoneNum);
				// jumpToActivityByType("更换轮胎");
			}
		});
		layout_other.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CheckUtil.isEmpty(PrefUtils.getString(
						SaladMainActivity.this, Common.PREF_MY_INFO, ""))) {
					Toast.makeText(SaladMainActivity.this, "您未设置个人信息，请先录入个人信息",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Log.i("TAG", "OTHER");
				currentTaskType = "其他";
				getCurrentTask(phoneNum);
				// jumpToActivityByType("其他");
			}
		});

		View view = (View) this.findViewById(R.id.menu_item_home);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AutoServiceProcess process = new AutoServiceProcess();
				process.setContext(SaladMainActivity.this);
				process.getSellerTypes();
				SaladMainActivity.this.finish();
			}

		});

		view = (View) this.findViewById(R.id.menu_item_mine);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// UserInfo userInfo = CarmapApplication.getInstance().userInfo;
				// if (userInfo == null) {
				// SaladMainActivity.this.startActivity(new Intent(
				// SaladMainActivity.this, LoginActivity.class));
				// } else {
				// SaladMainActivity.this.startActivity(new Intent(
				// SaladMainActivity.this, ProfileActivity.class));
				// }
				SaladMainActivity.this.startActivity(new Intent(
						SaladMainActivity.this, MineInfoActivity.class));
				SaladMainActivity.this.finish();

			}

		});

		View typeView = (View) this.findViewById(R.id.menu_item_type);
		typeView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LiveServiceProcess process = new LiveServiceProcess();
				process.setContext(SaladMainActivity.this);
				process.getSellerTypes();
				SaladMainActivity.this.finish();
			}

		});

	}

	// EventsBus
	@Subscribe(threadMode = ThreadMode.MainThread)
	public void onEventMainThread(JobEvents.JobSuccess e) {
		if (e.getJobCode() == JobEvents.SEND_SERVICE_REQUESTS) {
			OkHttpResponseData msg = (OkHttpResponseData) e.getResult();
			if (pd != null)
				pd.dismiss();
			if (msg != null) {
				dealSerciceRequestResult(msg);
			} else {
				Toast.makeText(SaladMainActivity.this, "任务请求失败",
						Toast.LENGTH_SHORT).show();
			}
		} else if (e.getJobCode() == JobEvents.GET_CURRENT_TASK) {
			if (pd != null)
				pd.dismiss();
			OkHttpResponseData msg = (OkHttpResponseData) e.getResult();
			Log.i("TAG", "GET_CURRENT_TASK");
			if (msg != null) {
				dealCurrentTaskResult(msg);
			} else {
				Toast.makeText(SaladMainActivity.this, "获取当前任务信息失败",
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	@Subscribe(threadMode = ThreadMode.MainThread)
	public void onEventMainThread(JobEvents.JobFailure e) {
		if (e.getJobCode() == JobEvents.SEND_SERVICE_REQUESTS) {
			Toast.makeText(SaladMainActivity.this, "网络请求失败-上传任务",
					Toast.LENGTH_SHORT).show();
			if (pd != null)
				pd.dismiss();
		} else if (e.getJobCode() == JobEvents.GET_CURRENT_TASK) {
			Toast.makeText(SaladMainActivity.this, "网络请求失败-获取当前任务信息",
					Toast.LENGTH_SHORT).show();
			if (pd != null)
				pd.dismiss();
		}
	}

	private void dealCurrentTaskResult(OkHttpResponseData msg) {
		int hasCurrent = 0; // 0 无当前任务 1有当前任务
		int code = msg.getCode();
		if (code == 0) {
			try {
				String data = msg.getData();
				if (CheckUtil.isEmpty(data)) {
					Toast.makeText(SaladMainActivity.this, "当前任务获取失败",
							Toast.LENGTH_SHORT).show();
					return;
				}
				JSONObject json = new JSONObject(msg.getData());
				if (CheckUtil.isEmpty(json.toString())) {
					Toast.makeText(SaladMainActivity.this, "当前任务获取失败",
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (json.has("service_request")) {
					String currentTask = json.getString("service_request");
					if (!CheckUtil.isEmpty(currentTask)) {
						hasCurrent = 0;
						Toast.makeText(SaladMainActivity.this, "当前有未完成的任务",
								Toast.LENGTH_LONG).show();
					} else {
						PrefUtils.putString(SaladMainActivity.this,
								Common.PREF_CURRENT_TASK, "");
//						hasCurrent = 1;
//						jumpToActivityByType(currentTaskType);
					}

				} else {
					PrefUtils.putString(SaladMainActivity.this,
							Common.PREF_CURRENT_TASK, "");
					hasCurrent = 1;
					jumpToActivityByType(currentTaskType);
				}

			} catch (JSONException e) {
				Toast.makeText(SaladMainActivity.this, "当前任务获取失败",
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				return;
			}
		} else {
			Toast.makeText(SaladMainActivity.this, msg.getMsg(),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 跳转服务详情页面 一人一个任务逻辑 先查询是否有当前任务 有则提示不能请求服务
	 * 
	 * @param type
	 */
	private void jumpToActivityByType(String serviceType) {
		if (pd == null) {
			pd = new ProgressDialog(SaladMainActivity.this);
		}

		pd.setTitle("正在上传任务信息...");
		pd.show();
		Job job = new ServiceRequestJob(serviceType);
		CarmapApplication.getInstance().getJobManager().addJobInBackground(job);
	}

	/**
	 * 获取当前任务信息
	 * 
	 * @param phoneNum
	 */
	private void getCurrentTask(String phoneNum) {
		// 先进行网络请求，查看是否包含未完成的任务
		if (pd == null) {
			pd = new ProgressDialog(SaladMainActivity.this);
		}
		pd.setTitle("正在获取当前任务信息...");
		pd.show();
		Job getCurrentTaskJob = new GetCurrentTaskJob(phoneNum);
		CarmapApplication.getInstance().getJobManager()
				.addJobInBackground(getCurrentTaskJob);
	}

	private void dealSerciceRequestResult(OkHttpResponseData msg) {

		int code = msg.getCode();
		if (code == 0) {
			try {
				String data = msg.getData();
				if (CheckUtil.isEmpty(data)) {
					Toast.makeText(SaladMainActivity.this, "任务上传失败",
							Toast.LENGTH_SHORT).show();
					return;
				}
				JSONObject json = new JSONObject(msg.getData());
				if (json.has("service_request")) {
					String service_request = json.getString("service_request");
					if (!CheckUtil.isEmpty(service_request)) {
						JSONObject idJson = new JSONObject(service_request);
						if (idJson != null) {
							// 返回值中应该有任务的详细信息
							if (idJson.has("id")) {
								PrefUtils.putString(SaladMainActivity.this,
										Common.PREF_CURRENT_TASK_ID,
										idJson.getString("id"));
								EventBus.getDefault()
										.post(new JobEvents.JobSuccess<>(
												JobEvents.SEND_SERVICE_REQUESTS_SUCCESS));
							} else {
								Toast.makeText(SaladMainActivity.this,
										"任务上传失败", Toast.LENGTH_SHORT).show();
							}
						}
					} else {
						Toast.makeText(SaladMainActivity.this, "任务上传失败",
								Toast.LENGTH_SHORT).show();
					}

				} else {
					Toast.makeText(SaladMainActivity.this, "任务上传失败",
							Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				Toast.makeText(SaladMainActivity.this, "任务上传失败",
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				return;
			}
			// 保存当前任务信息
		} else {
			Toast.makeText(SaladMainActivity.this, msg.getMsg(),
					Toast.LENGTH_SHORT).show();
		}

	}
}
